package pkg

import (
	"demo_bff/global"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
func SetJwtToken(payload string) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + global.ServerConfig.JwtConfig.Seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(global.ServerConfig.JwtConfig.SecretKey))
}

func GetJwtTokenPayload(tokenString string) (string, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(global.ServerConfig.JwtConfig.SecretKey), nil
	})
	if err != nil {
		return "", errors.New("token解析失败")
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims["payload"].(string), err
	}
	return "", errors.New("token解析失败")
}
